<template>
  <div class="chart-design">
    <el-header class="cd-header">
      <!--横向工具栏-->
      <el-page-header @back="$router.back()">
        <el-row slot="content" type="flex" align="middle" justify="space-between">
          <span>
            <span> {{ viewType === 'view' ? '指标预览' : '指标探源' }}</span>
            <span v-if="!!panelInfo.name">
              <span class="px-1">-</span>
              <span>{{ panelInfo.name }}</span>
            </span>
          </span>
          <div>
            <el-button
              v-if="viewType === 'edit' && componentData && componentData.length > 0"
              icon="el-icon-view"
              @click="onViewTypeToggle"
            >
              预览
            </el-button>
            <el-button v-if="viewType === 'view'" icon="el-icon-edit" @click="onViewTypeToggle">重新探源</el-button>
            <el-button v-if="viewType === 'edit'" type="primary" icon="el-icon-check" @click="onSaveClick">
              保存
            </el-button>
          </div>
        </el-row>
      </el-page-header>
    </el-header>
    <el-container class="cd-container">
      <el-main class="cd-main">
        <div class="cd-content">
          <!-- 查看 -->
          <div class="view-wrapper">
            <chart-design-view ref="view" />
          </div>
          <div class="actions">
            <strong class="ml-4">图表类型</strong>
            <el-select v-model="chartType" placeholder="请选择图表类型" class="ml-4" @change="onChartTypeChange">
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <!-- 探源 -->
          <div v-show="viewType === 'edit'" class="edit-wrapper">
            <chart-design-edit ref="editForm" :panel="panelInfo" />
          </div>
        </div>
      </el-main>
      <el-aside class="cd-side" width="350px">
        <ChartDesignSetting
          v-if="viewType === 'view'"
          ref="settingRef"
          :visible="viewType === 'view'"
          :chart-edit-param="chartEditParam"
        />
        <chart-design-definition v-else />
      </el-aside>
    </el-container>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { uuid } from 'vue-uuid'

import { initPanelData, panelUpdate } from '@/api/panel/panel'
import { pluginTypes } from '@/api/chart/chart'

import { deepCopy, getNowCanvasComponentData, matrixBaseChange, imgUrlTrans } from '@/components/canvas/utils/utils'
import componentList, { COMMON_BACKGROUND } from '@/components/canvas/customComponent/component-list' // 左侧列表数据
import { adaptCurThemeCommonStyle } from '@/components/canvas/utils/style'

import ChartDesignEdit from './design/edit.vue'
import ChartDesignView from './design/view.vue'
import ChartDesignDefinition from './design/definition.vue'
import ChartDesignSetting from './design/setting.vue'

export default {
  components: { ChartDesignEdit, ChartDesignView, ChartDesignDefinition, ChartDesignSetting },
  provide() {
    return {
      settings: ['edit', 'delete', 'style'],
    }
  },
  data() {
    return {
      viewType: 'edit',
      canvasId: 'canvas-main',
      chartType: '',
      typeOptions: [
        { value: 'line', label: '折线图' },
        { value: 'bar', label: '柱状图' },
        { value: 'pie', label: '饼图' },
      ],
    }
  },
  computed: {
    ...mapState({
      componentGap: 'componentGap',
      componentData: 'componentData',
      canvasStyleData: 'canvasStyleData',
      curCanvasScaleMap: 'curCanvasScaleMap',
      curComponent: 'curComponent',
      panelInfo: (state) => state.panel.panelInfo || {},
    }),
    curCanvasScaleSelf() {
      return this.curCanvasScaleMap[this.canvasId]
    },
    customCanvasStyle() {
      let style = {
        padding: this.componentGap + 'px',
      }

      if (this.canvasStyleData.openCommonStyle) {
        if (
          this.canvasStyleData.panel.backgroundType === 'image' &&
          typeof this.canvasStyleData.panel.imageUrl === 'string'
        ) {
          style = {
            background: `url(${imgUrlTrans(this.canvasStyleData.panel.imageUrl)}) no-repeat`,
            ...style,
          }
        } else if (this.canvasStyleData.panel.backgroundType === 'color') {
          style = {
            background: this.canvasStyleData.panel.color,
            ...style,
          }
        }
      }
      return style
    },
    mainCanvasComponentData() {
      return getNowCanvasComponentData(this.canvasId)
    },
    // 侧边显示控制
    chartEditParam() {
      if (this.curComponent) {
        if (this.curComponent.type === 'view') {
          return { id: this.curComponent.propValue.viewId, optType: 'edit' }
        } else if (this.curComponent.type === 'de-tabs' && this.$store.state.chart.viewId) {
          return { id: this.$store.state.chart.viewId, optType: 'edit' }
        } else {
          return {}
        }
      }
      return this.curComponent ? { id: this.curComponent.propValue.viewId, optType: 'edit' } : {}
    },
  },
  watch: {
    '$route.query.panelId': function (val) {
      if (this.$route.name === 'ChartDesign' && val) {
        this.init()
      }
    },
    'curComponent.propValue.innerType': {
      handler: function (val) {
        // console.log('curComponent.propValue.innerType change, val=', val)
        if (this.chartType !== val) {
          this.chartType = val
        }
      },
      deep: true,
    },
  },
  created() {
    this.init()
  },
  mounted() {
    localStorage.removeItem('plugin-views')
    pluginTypes()
      .then((res) => {
        const plugins = res.data
        localStorage.setItem('plugin-views', JSON.stringify(plugins))
        this.$store.commit('initViewRender', plugins)
      })
      .catch((e) => {
        localStorage.setItem('plugin-views', null)
        this.$store.commit('initViewRender', [])
      })
  },
  methods: {
    init() {
      const panelId = this.$route.query.panelId
      console.log('chart design init() panelId=', panelId)
      initPanelData(panelId, false, (res) => {
        // console.log('initPanelData res=', res)
        if (this.componentData && this.componentData.length > 0) {
          // 进入本界面时，若有图表数据，则优先显示为图表
          this.viewType = 'view'
          this.$store.commit('setCurComponent', {
            component: this.componentData[0],
            index: 0,
          })
        } else {
          this.viewType = 'edit'
        }
      })
    },
    newViewInfo(newViewInfo) {
      console.log('info=', newViewInfo)
      let component
      const newComponentId = uuid.v1()
      // 用户视图设置 复制一个模板
      componentList.forEach((componentTemp) => {
        if (componentTemp.type === 'view') {
          component = matrixBaseChange(deepCopy(componentTemp))
          const propValue = {
            id: newComponentId,
            viewId: newViewInfo.id,
            textValue: this.panelInfo.name,
          }
          component.propValue = propValue
          component.filters = []
          component.linkageFilters = []
          component.sizex = 140 // 横向填满，140没有找到依据，仅仅是根据实验得来,
          component.sizey = 72 // 纵向填满，72没有找到依据，仅仅是根据实验得来
        }
      })
      component.auxiliaryMatrix = this.canvasStyleData.auxiliaryMatrix
      // position = absolution 或导致有偏移 这里中和一下偏移量
      if (this.canvasStyleData.auxiliaryMatrix) {
        component.style.left = (component.x - 1) * this.curCanvasScaleSelf.matrixStyleOriginWidth
        component.style.top = (component.y - 1) * this.curCanvasScaleSelf.matrixStyleOriginHeight
        component.style.width = component.sizex * this.curCanvasScaleSelf.matrixStyleOriginWidth
        component.style.height = component.sizey * this.curCanvasScaleSelf.matrixStyleOriginHeight
      } else {
        component.style.left = 0
        component.style.top = 0
        component.x = 1
        component.y = 1
      }
      component['canvasId'] = 'canvas-main'
      component['canvasPid'] = '0'
      component.id = newComponentId
      // 统一设置背景信息
      component.commonBackground = deepCopy(COMMON_BACKGROUND)
      // 适配当前主题
      adaptCurThemeCommonStyle(component)
      this.$store.commit('setComponentData', [])
      this.$store.commit('recordSnapshot', 'clearCanvas')
      this.$store.commit('addComponent', { component })
      this.$store.commit('recordSnapshot', 'newViewInfo')
      this.$store.commit('setCurComponent', { component: component, index: this.componentData.length - 1 })
    },
    onViewTypeToggle() {
      this.viewType = this.viewType === 'edit' ? 'view' : 'edit'
    },
    onChartTypeChange(val) {
      console.log('onChartTypeChange val=', val)
      if (!val) {
        return
      }
      this.$refs.settingRef && this.$refs.settingRef.changeChartType(val)
      this.$nextTick(() => {
        // 必须生效之后才能正确提交
        this.$refs.editForm && this.$refs.editForm.saveConfig()
      })
    },
    savePrepare() {
      // 保存到数据库
      const panelInfo = this.$store.state.panel.panelInfo
      const requestInfo = {
        id: panelInfo.id,
        watermarkOpen: panelInfo.watermarkOpen,
        panelStyle: JSON.stringify(this.canvasStyleData),
        panelData: JSON.stringify(this.componentData),
      }
      const components = deepCopy(this.componentData)
      components.forEach((view) => {
        // 清理联动信息
        if (view.linkageFilters && view.linkageFilters.length > 0) {
          view.linkageFilters.splice(0, view.linkageFilters.length)
        }
        if (view.DetailAreaCode) {
          view.DetailAreaCode = null
        }
        if (view.filters && view.filters.length > 0) {
          view.filters = []
        }
        if (view.type === 'de-tabs') {
          view.options.tabList &&
            view.options.tabList.length > 0 &&
            view.options.tabList.forEach((tab) => {
              if (tab.content && tab.content.filters && tab.content.filters.length > 0) {
                tab.content.filters = []
              }
            })
        }
      })
      // 无需保存条件
      requestInfo.panelData = JSON.stringify(components)
      return requestInfo
    },
    onSaveClick() {
      if (this.$refs.editForm) {
        this.$refs.editForm.validate((valid, done) => {
          if (valid) {
            this.handleSave()
            done()
          } else {
            return false
          }
        })
      } else {
        this.handleSave()
      }
    },
    async handleSave() {
      try {
        if (this.$refs.editForm) {
          // 重新探源时
          const viewInfo = await this.$refs.editForm.submit()
          if (!viewInfo.id) {
            return
          }
          this.newViewInfo(viewInfo)
        }

        const params = this.savePrepare()
        await panelUpdate(params)
        this.$store.commit('refreshSaveStatus')
        this.$message({
          message: this.$t('commons.save_success'),
          type: 'success',
          showClose: true,
        })
        this.viewType = 'view'
      } catch (error) {
        console.log('handleSave error=', error)
        this.$message.error('保存失败，请稍后重试')
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.chart-design {
  background-color: #fff;
  height: calc(100vh - 133px);
  .cd-header {
    display: flex;
    align-items: center;
    border-bottom: 1px solid rgba(0, 0, 0, 0.08);
    ::v-deep .el-page-header__title {
      align-self: center;
    }

    ::v-deep .el-page-header {
      width: 100%;
    }
    ::v-deep .el-page-header__content {
      flex: 1;
    }
  }

  .cd-container {
    height: calc(100% - 60px);
    .cd-main {
      height: 100%;
      .cd-content {
        height: 100%;
        width: 100%;
        position: relative;

        .view-wrapper,
        .edit-wrapper {
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
          background-color: #fff;
        }

        .view-wrapper {
          top: 40px;
          height: calc(100% - 40px);
        }
        .actions {
          position: absolute;
          top: 0;
          left: 0;
          display: flex;
          align-items: center;
        }
      }
    }
    .cd-side {
      border-left: 1px solid rgba(0, 0, 0, 0.08);
    }
  }
}
</style>
